package org.cancerregulome.redi.websvc.model;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.systemsbiology.addama.jsonconfig.Mapping;
import org.systemsbiology.addama.jsonconfig.MappingsHandler;
import org.systemsbiology.addama.jsonconfig.impls.MappingPropertyByIdContainer;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hrovira
 */
public class DatasetModelsByIdMappingsHandler
        extends MappingPropertyByIdContainer<Map<String, DatasetModel>>
        implements MappingsHandler {

    public DatasetModelsByIdMappingsHandler(Map<String, Map<String, DatasetModel>> map) {
        super(map);
    }

    public void handle(Mapping mapping) throws Exception {
        HashMap<String, DatasetModel> models = new HashMap<String, DatasetModel>();

        String rootPath = mapping.JSON().getString("rootPath");
        File f = new File(rootPath);
        if (f.exists() && f.isDirectory()) {
            FileAlterationMonitor monitor = new FileAlterationMonitor();
            FileAlterationObserver rootObserver = new FileAlterationObserver(f);
            rootObserver.addListener(new DatasetModelAlterationListener(f, models));
            monitor.addObserver(rootObserver);
            monitor.start();
        }

        addValue(mapping, models);
    }
}
